package com.hnzq.cloud.freshsendmessage.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hnzq.cloud.OrderAPI;
import com.hnzq.cloud.dto.AddOrderDto;
import com.hnzq.cloud.dto.OrderDto;
import com.hnzq.cloud.model.Result;
import com.hnzq.cloud.param.AddOrderParam;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 周皓月
 * @since 2022-02-11
 */
@RestController
@RequestMapping("/SendCreateOrderMessage")
@Slf4j
public class SendCreateOrderController {

    /**
     * 订单接口
     */
    @Autowired
    private OrderAPI orderAPI;



    /**
     * 消息队列模板对象
     */
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    //通过ObjectMapper进行JSON字符串与java对象的序列化
    ObjectMapper mapper = new ObjectMapper();

    /**
     * 创建订单
     * @return
     */
    @GetMapping("createOrderAndSend")
    public Result createOrderAndSend(@RequestBody AddOrderParam addOrderParam){

        //从登录中获取到userId
        Integer userId = mapper.convertValue(((ServletRequestAttributes)
                (RequestContextHolder.currentRequestAttributes())).getRequest()
                .getHeader("userId"), Integer.class);

        addOrderParam.setUserId(userId);

        AddOrderDto addOrderDto = orderAPI.addOrder(addOrderParam).getData();


        //存数据库

        //发送消息，设置超时时间
        rocketMQTemplate.syncSend("order_topic",
                MessageBuilder.withPayload(addOrderDto.getOrderId()).build(),
                3000L,
                14);
        log.info("订单已经发送到mq:{}",addOrderDto.getOrderId());

        return Result.newInstance().setMessage("订单发送成功");
    }

    /**
     * 修改支付状态,微信支付
     * @param orderId
     * @return
     */
    @GetMapping("dealWithOrderInWX")
    public Result dealWithOrderInWX(@RequestParam("orderId") Integer orderId) throws JsonProcessingException {
        //调用支付
        orderAPI.payForWX(orderId);
        //查询订单
        Result<OrderDto> order = orderAPI.findOrderByOrderId(orderId);
        //发送消息
        rocketMQTemplate.asyncSend("pay_Success", order.getData(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("发送消息：{}",sendResult);
            }

            @Override
            public void onException(Throwable e) {
                log.warn("发送异常",e);
            }
        });
        return Result.newInstance().setMessage("支付完成，已发送消息");
    }

    /**
     * 修改支付状态,支付宝支付
     * @param orderId
     * @return
     */
    @GlobalTransactional
    @GetMapping("dealWithOrderInZFB")
    public Result dealWithOrderInZFB(@RequestParam("orderId") Integer orderId) throws JsonProcessingException {
        //调用支付
        orderAPI.payForZFB(orderId);
        //查询订单
        Result<OrderDto> order = orderAPI.findOrderByOrderId(orderId);
        //发送消息
        rocketMQTemplate.asyncSend("pay_Success", order.getData(), new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                log.info("发送消息：{}",sendResult);
            }

            @Override
            public void onException(Throwable e) {
                log.warn("发送异常",e);
            }
        });
        return Result.newInstance().setMessage("支付完成，已发送消息");
    }
}
